var YPSE = {
	BASE : "http://www.yupoo.com/api/rest/",
	APIKEY : "89fcae28161282efad580f4ed7cd547b",
	METHOD_PHOTO : "yupoo.photos.getContext",
	METHOD_POOL : "yupoo.groups.pools.getContext",
	METHOD_ALBUM : "yupoo.albums.getContext",
	METHOD_PHOTOINFO : "yupoo.photos.getInfo",
    METHOD_POOLPHOTO : "yupoo.groups.pools.getPhotos",
    METHOD_ALBUMPHOTO : "yupoo.albums.getPhotos"
};
var RES = {
	ICON_PLAY_BACKWARD : "chrome://yupoostream/skin/play_backward.png",
	ICON_PLAY_FORWARD : "chrome://yupoostream/skin/play_forward.png",
	ICON_PREV : "chrome://yupoostream/skin/prev.png",
	ICON_NEXT : "chrome://yupoostream/skin/next.png",
	ICON_PLAY_SMALL : "chrome://yupoostream/skin/play_small",
	ICON_PAUSE : "chrome://yupoostream/skin/pause.png",
	ICON_QUIT : "chrome://yupoostream/skin/close.png"
};

var Boxes = {
	BACKGROUND : "yupoostream_back"

};

var currentDirection = "unknown";
var currentPhoto = null;
var photos = [];
var channel = "all";// album,pool
var cursor = 0;
var zindex = 0;
var centerPoint = {x:0,y:0};
var period ;
var currentAlbum = null;
var currentPool = null;
function view(url) {
	var map = getParams();
	if (map['id']) {
		var body = document.getElementsByTagName("body")[0];
		var back = $("yupoostream_back");
		if (back == null) {
			var back = document.createElement("div");
			back.setAttribute("id", "yupoostream_back");
			back.setAttribute("class", "backgroundOverlay");
			back
					.setAttribute(
							"style",
							"background-color:black;height:100%;left:0pt;opacity:0.5;position:fixed;top:0pt;width:100%;z-index:5000;");

			body.appendChild(back);
		}

		var yupoostream_flow = $('yupoostream_flow');
		if (yupoostream_flow == null) {
			yupoostream_flow = document.createElement("div");
			yupoostream_flow.setAttribute("id", "yupoostream_flow");
			yupoostream_flow.setAttribute("class", "yupoostream_flow");
		}
		body.appendChild(yupoostream_flow);

		var yupoostream_toolbar = $('yupoostream_toolbar');
		if (yupoostream_toolbar == null) {
			yupoostream_toolbar = document.createElement("div");
			yupoostream_toolbar.setAttribute("id", "yupoostream_toolbar");
			yupoostream_toolbar.setAttribute("class", "yupoostream_toolbar");
		}
		new Element("div", {
			'id' : 'yupoostream_prev',
			'class' : 'toolbutton',
			'style' : 'background:url("' + this.RES.ICON_PREV + '")',
			'onclick' : 'prev();'
		}).inject(yupoostream_toolbar);
		new Element("div", {
			'id' : 'yupoostream_playbackward',
			'class' : 'toolbutton',
			'style' : 'background:url("' + this.RES.ICON_PLAY_BACKWARD + '")',
			'onclick' : 'playBackward();'
		}).inject(yupoostream_toolbar);
		new Element("div", {
			'id' : 'yupoostream_playforward',
			'class' : 'toolbutton',
			'style' : 'background:url("' + this.RES.ICON_PLAY_FORWARD + '")',
			'onclick' : 'playForward();'
		}).inject(yupoostream_toolbar);
		new Element("div", {
			'id' : 'yupoostream_next',
			'class' : 'toolbutton',
			'style' : 'background:url("' + this.RES.ICON_NEXT + '")',
			'onclick' : 'next();'
		}).inject(yupoostream_toolbar);
		body.appendChild(yupoostream_toolbar);

		getPhotoInfo(url);
	}
}

function playForward() {
    pause();
    var url = RES.ICON_PAUSE;
    $('yupoostream_playforward').setStyles("background:url('"+ url + "');");
    $('yupoostream_playforward').removeEvents('click');
    $('yupoostream_playforward').addEvent('click',pause);
    currentDirection = "next";
    next();
    period = next.periodical(5000);
}
function playBackward() {
    pause();
    var url = RES.ICON_PAUSE;
    $('yupoostream_playbackward').setStyles("background:url('"+ url + "');");
    $('yupoostream_playbackward').removeEvents('click');
    $('yupoostream_playbackward').addEvent('click',pause);
    currentDirection = "prev";
    prev();
    period = prev.periodical(5000);
}

function pause() {
    if (currentDirection == "prev") {
        var url = RES.ICON_PLAY_BACKWARD;
	    $('yupoostream_playbackward').setStyles("background:url('"+ url + "');");
        $('yupoostream_playbackward').removeEvents('click');
        $('yupoostream_playbackward').addEvent('click',playBackward);
    } else {
        var url = RES.ICON_PLAY_FORWARD;
	    $('yupoostream_playforward').setStyles("background:url('"+ url + "');");
        $('yupoostream_playforward').removeEvents('click');
        $('yupoostream_playforward').addEvent('click',playForward);
    }
    $clear(period);
}

function prev() {
	currentDirection = "prev";
	var i = photos.indexOf(currentPhoto);
	if (!startGet) {
    	getData();
	}
	if (photos[i-1]) {
		if ($('yupoostream_right1')) {
			var fx1 = new Fx.Styles($('yupoostream_right1'), {duration:400, wait:false, fps:60});
			fx1.start({"opacity":0,"width":0,"height":0, "left":getWidth()}).chain(function() {
				$('yupoostream_right1').remove();
			});
		}
		
		var small = getSmallerDimensions(currentPhoto);
		var fx2 = new Fx.Styles($('yupoostream_main'), {duration:400, wait:false, fps:60});
		fx2.start({
//            'right':parseInt(centerPoint.x+photos[i+1].width/2+100), 
					'left': parseInt(centerPoint.x+photos[i-1].width/2+60),
					'opacity':0.25, 
					'width':small[0],
					'height':small[1],
					'bottom':parseInt(centerPoint.y-small[1]/2)}
                    ).chain(function(){
			$('yupoostream_main').addEvent('mouseover',function(event){
				this.style.opacity=1;
			});
			$('yupoostream_main').addEvent('mouseout',function(event){
				this.style.opacity=0.25;
			});
			$('yupoostream_main').removeEvents('click');
			$('yupoostream_main').addEvent('click',next);
			$('yupoostream_main').setAttribute('id','yupoostream_right1');
		});
		
		var fx3 = new Fx.Styles($('yupoostream_left1'), {duration:400, wait:false, fps:60});
		currentPhoto = photos[i-1];
		fx3.start({'left':parseInt(centerPoint.x-photos[i-1].width/2),
					'bottom':parseInt(centerPoint.y-photos[i-1].height/2),
					'position':'absolute',
					'border':'5px #fff solid',
					'z-index':5010,
					'width':parseInt(photos[i-1].width),
					'height':parseInt(photos[i-1].height),
					'opacity':1
					}).chain(function(){
						$('yupoostream_left1').removeEvents('click');
						$('yupoostream_left1').addEvent('click',info);
						$('yupoostream_left1').removeEvents('mouseover');
						$('yupoostream_left1').removeEvents('mouseout');
                        $('yupoostream_left1').setAttribute('id','yupoostream_main');
                        setLeftPhoto();
					});
	} else {
		if (i==0 && photos[0]== null) {
			if (period) {
				$clear(period);
			}
		}
	}
}

function next() {
	currentDirection = "next";
	var i = photos.indexOf(currentPhoto);
	if (!startGet) {
    	getData();
	}
	if (photos[i+1]) {
		if ($('yupoostream_left1')) {
			var fx1 = new Fx.Styles($('yupoostream_left1'), {duration:400, wait:false, fps:60});
			fx1.start({"opacity":0,"width":0,"height":0, "left":-$('yupoostream_left1').width}).chain(function() {
				$('yupoostream_left1').remove();
			});
		}
		var small = getSmallerDimensions(currentPhoto);
		var fx2 = new Fx.Styles($('yupoostream_main'), {duration:400, wait:false, fps:60});
		fx2.start({
//            'right':parseInt(centerPoint.x+photos[i+1].width/2+100), 
					'left': parseInt((centerPoint.x-photos[i+1].width/2-60)-small[0]),
					'opacity':0.25, 
					'width':small[0],
					'height':small[1],
					'bottom':parseInt(centerPoint.y-small[1]/2)}
                    ).chain(function(){
			$('yupoostream_main').addEvent('mouseover',function(event){
				this.style.opacity=1;
			});
			$('yupoostream_main').addEvent('mouseout',function(event){
				this.style.opacity=0.25;
			});
			$('yupoostream_main').addEvent('click',prev);
			$('yupoostream_main').removeEvent('click',info);
			$('yupoostream_main').setAttribute('id','yupoostream_left1');
		});
		var fx3 = new Fx.Styles($('yupoostream_right1'), {duration:400, wait:false, fps:60});
		currentPhoto = photos[i+1];
		fx3.start({'left':parseInt(centerPoint.x-photos[i+1].width/2),
					'bottom':parseInt(centerPoint.y-photos[i+1].height/2),
					'position':'absolute',
					'border':'5px #fff solid',
					'z-index':5010,
					'width':parseInt(photos[i+1].width),
					'height':parseInt(photos[i+1].height),
					'opacity':1
					}).chain(function(){
						$('yupoostream_right1').removeEvents('click');
						$('yupoostream_right1').addEvent('click',info);
						$('yupoostream_right1').removeEvents('mouseover');
						$('yupoostream_right1').removeEvents('mouseout');
                        $('yupoostream_right1').setAttribute('id','yupoostream_main');
                        setRightPhoto();
					});
	} else {
		if (photos.length > i+1) {
			if (period) {
				$clear(period);
			}
		}
	}
	
}

function info() {
//	alert('info');
}

function getPhotoInfo(url) {
	var x = new XMLHttpRequest();
	x.open("GET", getPhotoURL(url));
	x.onreadystatechange = function() {
		if (x.readyState != 4)
			return false;
		if (x.status == 200) {
			obj = Json.evaluate(x.responseText);
			var stat = obj.stat;
			if (stat == 'ok') {
				currentPhoto = obj.photo;
				addPhoto(obj.photo);
			} else {

			}
		} else {

		}
		return true;
	}.bind(this);
	x.send(null);
	return true;
}

function addPhoto(photo, where) {
	var box = $('yupoostream_flow');
	var photoURL = getPhotoElement(photo);
	new Asset.images([photoURL], {
		onComplete : function() {
			var photoEle = new Image();
			photoEle.src = photoURL;
			photoEle.id = "yupoostream_photo_" + photo.id;
			photoEle.setAttribute("class", "yupoostream_photo");
			photoEle.alt = photo.title;
			if (where == "head") {
				photos.shift(photo);
				photoEle.injectTop(box);
			} else {
				photos.push(photo);
				photoEle.inject(box);
			}
		}
	});
}

function getPhotoElement(photo) {
	if (photo != null) {
        
		var photoURL = "http://photo" + photo.host + ".yupoo.com/" + photo.dir
				+ "/" + photo.filename + "/big/";

		return photoURL;
	}
}
var context = [];
function getPhotoContext(id, onSuccess,onFailure) {
	var x = new XMLHttpRequest();
	x.open("GET", makeURL(id));
	this.context = new Array();
	x.onreadystatechange = function() {
		if (x.readyState != 4)
			return false;
		if (x.status == 200) {
			var obj = Json.evaluate(x.responseText);
			var stat = obj.stat;
			if (stat == 'ok') {
				if (onSuccess) onSuccess(x);
			} else {
				if (onFailure) onFailure(x);
			}
		} else {

		}
	}.bind(this);
	x.send(null);
	return this.context;
}

function getPhotoURL(url) {
	var map = getParams(url);
	if (currentPhoto != null) {
		map['id'] = currentPhoto.id;
	}
	return YPSE.BASE + "?method=" + YPSE.METHOD_PHOTOINFO + "&api_key="
			+ YPSE.APIKEY + "&photo_id=" + map['id'] + "&format=json";
}
function makeURL(id) {
	if (!id) {
		var map = getParams();
		if (currentPhoto != null) {
			map['id'] = currentPhoto.id;
		}
		id = map['id'];
	}
    if (currentAlbum) {
		return YPSE.BASE + "?method=" + YPSE.METHOD_ALBUM + "&api_key="
				+ YPSE.APIKEY + "&photo_id=" + id + "&album_id=" + currentAlbum + "&format=json";
    } else if (currentPool) {
		return YPSE.BASE + "?method=" + YPSE.METHOD_POOL + "&api_key="
				+ YPSE.APIKEY + "&photo_id=" + id + "&group_id=" + currentPool + "&format=json";
    }
	return YPSE.BASE + "?method=" + YPSE.METHOD_PHOTO + "&api_key="
			+ YPSE.APIKEY + "&photo_id=" + id + "&format=json";
}

function getParams(url) {
	var map = new Object;
	if (!url) {
		url = window.location.search;
	}
	if (url.indexOf("?") != -1) {
		var str = url.substr(1)
		strs = str.split("&");
		for (i = 0; i < strs.length; i++) {
			var key = strs[i].split("=")[0];
			var value = strs[i].split("=")[1]
			map[key] = value;
		}
	}
	if (map['album']) {
		channel = "album";
	}
	if (map['pool']) {
		channel = "pool"
	}
	return map;
}

function init(option) {
    if (window.location.toString().indexOf("yupoo.com/photos/view")<0) {
        return;
    }
    if (option) {
        if (option.type == 'album') {
            currentAlbum = option.id;
	        currentPool = null;
        } else if (option.type == 'pool') {
            currentPool = option.id;
	        currentAlbum = null;
        } else {
	        currentAlbum = null;
	        currentPool = null;
        }
    } else {
        currentAlbum = null;
        currentPool = null;
    }
    
    var cssCheck = $("yupoostream_css");
    if (cssCheck == null) { // insert stylesheet reference
      var css = document.createElement("link");
      css.setAttribute("id", "yupoostream_css");
      css.setAttribute("rel", "stylesheet");
      css.setAttribute("type", "text/css");
      css.setAttribute("media", "screen");
      css.setAttribute("href", "chrome://yupoostream/skin/yupoostream.css");
      var newCss = document.importNode(css,true);
      document.getElementsByTagName('head')[0].appendChild(newCss);
    }
    
	getCenterPoint();
	var map = getParams(null);
	if (map['id']) {
		var div = $('photoImgDiv'+map['id']);
		var currentList = $(div).getChildren();
		currentPhoto = {'id':map['id'],'src':currentList[0].src, 'title':currentList[0].alt, 'width':currentList[0].width, 'height':currentList[0].height};
		photos.push(currentPhoto);
		
		getPhotoContext(map['id'],function(x){
			photoJson = Json.evaluate(x.responseText);
			var srcPrev = '';
			var photoPrev = '';
			var photosLink = [];
			if (photoJson.context.prev) {
				photoPrev = photoJson.context.prev;
				srcPrev = getPhotoElement(photoPrev);
				photosLink.push(srcPrev);
			}
			var srcNext = '';
			var photoNext = '';
			if (photoJson.context.next) {
				photoNext = photoJson.context.next;
				srcNext = getPhotoElement(photoNext);
				photosLink.push(srcNext);
			}
			if (photosLink.length > 0) {
				new Asset.images(photosLink, {
					onComplete : function() {
						if (srcPrev != '') {
							var prev = new Image();
							prev.src = srcPrev;
							var prevObj = {'id':photoPrev.id,"src":srcPrev,"title":photoPrev.title,'width':prev.width,'height':prev.height};
							if (photos.indexOf(prevObj) < 0) {
								photos.unshift(prevObj);
								setLeftPhoto();
							}
						}
						if (srcNext != '') {
							var next = new Image();
							next.src = srcNext;
							var nextObj = {'id':photoNext.id,"src":srcNext,"title":photoNext.title,'width':next.width,'height':next.height};
							if (photos.indexOf(nextObj) < 0) {
								photos.push(nextObj);
								setRightPhoto();
							}
						}
					}
				});
			}
			
		});
	}
	setBackBox();
	setMainPhoto();
}
function setMainPhoto() {
	var mainImage = $("yupoostream_main");
	if (mainImage) {
        mainImage.src = currentPhoto.src;
        mainImage.title = currentPhoto.title;
	} else {
    	var  mainPhoto = new Element("img",{'src':currentPhoto.src,
						'id':"yupoostream_main",
						'alt':currentPhoto.title,
						'style':"left:"+parseInt(centerPoint.x-currentPhoto.width/2)+"px; " +
								"bottom:"+parseInt(centerPoint.y-currentPhoto.height/2)+"px; " +
								"position:fixed; " +
								"border:5px #fff solid;" +
								"z-index:5010;"
						});
//    cvi_reflex.add(mainPhoto);
        mainPhoto.inject($('yupoostream_flow'));
	}
}
function setLeftPhoto() {
	var i = photos.indexOf(currentPhoto);
	if (i>0) {
		if ($('yupoostream_left1')) {
			leftImage = $('yupoostream_left1');
			leftImage.src = photos[i-1].src;
			leftImage.alt = photos[i-1].title;
		} else {
			var ele = new Element("img",{'src':photos[i-1].src,
							'id':"yupoostream_left1",
							'alt':photos[i-1].title,
							'style':"right:"+parseInt(centerPoint.x+currentPhoto.width/2+100)+"px;" +
									"bottom:"+parseInt(centerPoint.y-getSmallerDimensions(photos[i-1])[1]/2)+"px; " +
									"position:fixed; " +
									"border:5px #fff solid;" +
                                    " opacity:0.25; " +
									"width:"+parseInt(getSmallerDimensions(photos[i-1])[0])+"px;" +
									"height:"+parseInt(getSmallerDimensions(photos[i-1])[1])+"px;" +
									"z-index:5009;"
							});
			ele.addEvent('mouseover', function() {this.style.opacity=1;});
			ele.addEvent('mouseout', function() {this.style.opacity=0.25;});
			ele.addEvent('click', prev);
			ele.injectTop($('yupoostream_flow'));
//            cvi_reflex.add(ele, { tilt:"right", iwidth:120 });
		}
	}
}
function setRightPhoto() {
	var i = photos.indexOf(currentPhoto);
	if (i<photos.length-1) {
		if ($('yupoostream_right1')) {
			rightImage = $('yupoostream_right1');
			rightImage.src = photos[i+1].src;
			rightImage.alt = photos[i+1].title;
		} else {
			var nextEle = new Element("img",{'src':photos[i+1].src,
							'id':"yupoostream_right1",
							'alt':photos[i+1].title,
							'style':"left:"+parseInt(centerPoint.x+currentPhoto.width/2+100)+"px; " +
									"bottom:"+parseInt(centerPoint.y-getSmallerDimensions(photos[i+1])[1]/2)+"px; " +
									"position:fixed; " +
                                    "border:5px #fff solid; " +
                                    "opacity:0.25; " +
									"width:"+parseInt(getSmallerDimensions(photos[i+1])[0])+"px; " +
									"height:"+parseInt(getSmallerDimensions(photos[i+1])[1])+"px;" +
									"z-index:5009;",
							});
			nextEle.addEvent('mouseover',function(){this.style.opacity=1});
			nextEle.addEvent('mouseout',function(){this.style.opacity=0.25});
			nextEle.addEvent('click',next);
			nextEle.inject($('yupoostream_flow'));
//			cvi_reflex.add(nextEle, { tilt:"left", iwidth:120 });
		}
	}
}

function getSmallerDimensions(photo) {
	var width = photo.width;
	var height = photo.height;
	if (width > height) {
		return [240,height*240/width];
	}
	return [width*240/height,240];
}


function setBackBox() {
	var body = document.getElementsByTagName("html")[0];
    $(body).setStyles({"overflow-x":"hidden","overflow-y":"hidden"});
	var back = $("yupoostream_back");
	if (back == null) {
		var back = document.createElement("div");
		back.setAttribute("id", "yupoostream_back");
		back.setAttribute("class", "backgroundOverlay");
		back
				.setAttribute(
						"style",
						"background-color:black;height:100%;left:0pt;opacity:0.9;position:fixed;top:0pt;width:100%;z-index:5000;");

		body.appendChild(back);
	}

	var yupoostream_flow = $('yupoostream_flow');
	if (yupoostream_flow == null) {
		yupoostream_flow = document.createElement("div");
		yupoostream_flow.setAttribute("id", "yupoostream_flow");
		yupoostream_flow.setAttribute("class", "yupoostream_flow");
	}
	body.appendChild(yupoostream_flow);

	var yupoostream_toolbar = $('yupoostream_toolbar');
	if (yupoostream_toolbar == null) {
		yupoostream_toolbar = document.createElement("div");
		yupoostream_toolbar.setAttribute("id", "yupoostream_toolbar");
		yupoostream_toolbar.setAttribute("class", "yupoostream_toolbar");
	
		var prevButton = new Element("div", {
			'id' : 'yupoostream_prev',
			'class' : 'toolbutton',
			'style' : 'background:url("' + this.RES.ICON_PREV + '")'
		})
        prevButton.addEvent('click',prev);
        prevButton.inject(yupoostream_toolbar);
        
		var backwardButton = new Element("div", {
			'id' : 'yupoostream_playbackward',
			'class' : 'toolbutton',
			'style' : 'background:url("' + this.RES.ICON_PLAY_BACKWARD + '")'
		})
        backwardButton.addEvent('click',playBackward);
        backwardButton.inject(yupoostream_toolbar);
		var forwardButton = new Element("div", {
			'id' : 'yupoostream_playforward',
			'class' : 'toolbutton',
			'style' : 'background:url("' + this.RES.ICON_PLAY_FORWARD + '")',
		});
        forwardButton.addEvent('click',playForward);
        forwardButton.inject(yupoostream_toolbar);
		
        var nextButton = new Element("div", {
			'id' : 'yupoostream_next',
			'class' : 'toolbutton',
			'style' : 'background:url("' + this.RES.ICON_NEXT + '")'
		});
        nextButton.addEvent('click',next);
        nextButton.inject(yupoostream_toolbar);
	    new Element("div", {
	        'id' :'yupoostream_quit',
	        'class' : 'toolbutton',
	        'style' : 'background:url("' + this.RES.ICON_QUIT + '");' +
	                    'position:fixed; right:3px; top:3px;' +
	                    'width:32px; height:32px;',
	        'onclick' : 'quit();'
	    }).inject(yupoostream_toolbar);
    }
	body.appendChild(yupoostream_toolbar);
}

function getCenterPoint() {
	var height = getHeight();
	var width = getWidth();
	this.centerPoint.x = width/2;
	this.centerPoint.y = height/2;
}

function getHeight() {
    var height = 0;
    if (window.content.document.compatMode == "CSS1Compat") {
        // standards mode
        height = window.content.document.documentElement.clientHeight;
    } else { //if (compatMode == "BackCompat") 
        // quirks mode
        height = window.content.document.body.clientHeight;
    }
    return height;
}
    
function getWidth() {
    if (window.content.document.compatMode == "CSS1Compat") {
        // standards mode
        return window.content.document.documentElement.clientWidth;
    } else { //if (compatMode == "BackCompat")
        // quirks mode
        return window.content.document.body.clientWidth;
    }
}
var startGet = false;
function getData() {
	startGet = true;
	if (currentDirection == "next") {
		var last = photos[photos.length-1];
		if (last != null) {
			getPhotoContext(last.id, function(x){
				photoJson = Json.evaluate(x.responseText);
				
				var photoNext = photoJson.context.next;
				if (photoNext) {
					var srcNext = getPhotoElement(photoNext);
					
					new Asset.images([srcNext], {
						onComplete : function() {
							var next = new Image();
							next.src = srcNext;
							var obj = {'id':photoNext.id,"src":srcNext,"title":photoNext.title,'width':next.width,'height':next.height};
							if (photos.indexOf(obj) < 0) {
								photos.push(obj);
	                            if (!$defined($('yupoostream_right1'))) {
								     setRightPhoto();
	                            }
							}
							startGet = false;
						}
					});
				} else {
					photos.push(null);
				}
			});
		}
	} else {
		var first = photos[0];
		if (first != null) {
			getPhotoContext(first.id, function(x){
				photoJson = Json.evaluate(x.responseText);
				
				var photoPrev = photoJson.context.prev;
				if (photoPrev) {
					var srcPrev = getPhotoElement(photoPrev);
					
					new Asset.images([srcPrev], {
						onComplete : function() {
							var prev = new Image();
							prev.src = srcPrev;
							var obj = {'id':photoPrev.id,"src":srcPrev,"title":photoPrev.title,'width':prev.width,'height':prev.height};
							if (photos.indexOf(obj) < 0) {
								photos.unshift(obj);
	                            if (!$defined($('yupoostream_left1'))) {
								     setLeftPhoto();
	                            }
							}
							startGet = false;
						}
					});
				} else {
					photos.unshift(null);
				}
			});
		}
	}
}

function quit() {
    var body = document.getElementsByTagName("html")[0];
    $(body).setStyles({"overflow-x":"auto","overflow-y":"scroll"});
    if (period) {
        $clear(period);
    }
    currentDirection = "unknown";
	currentPhoto = null;
	photos = [];
	channel = "all";// album,pool
	cursor = 0;
	zindex = 0;
	startGet = false;
    if ($('yupoostream_toolbar')) {
        $('yupoostream_toolbar').remove();
    }
    if ($('yupoostream_back')) {
        $('yupoostream_back').remove();
    }
    if ($('yupoostream_flow')) {
        $('yupoostream_flow').remove();
    }
    if ($('yupoostream_css')) {
        $('yupoostream_css').remove();
    }
}


function resize() {
	getCenterPoint();
	if ($('yupoostream_main')) {
		$('yupoostream_main').setStyles({"left":parseInt(centerPoint.x-currentPhoto.width/2),
										"bottom":parseInt(centerPoint.y-currentPhoto.height/2)});
	}
	if ($('yupoostream_left1')) {
		$('yupoostream_left1').setStyles({"right":parseInt(centerPoint.x+currentPhoto.width/2+100),
									"bottom":parseInt(centerPoint.y-getSmallerDimensions(photos[i-1])[1]/2)});
	}
	if ($('yupoostream_right1')) {
		$('yupoostream_right1').setStyles({"left":parseInt(centerPoint.x+currentPhoto.width/2+100),
									"bottom":parseInt(centerPoint.y-getSmallerDimensions(photos[i+1])[1]/2)});
	}
									
}
function yupoostreamload() {
//    cvi_reflex.defaultTilt = 'none'; //STR 'n|l|r'-'none|left|right'
//	cvi_reflex.defaultHeight = 33; //INT 10-100 (%)
//	cvi_reflex.defaultDistance = -33; //INT 0-100 (px)
//	cvi_reflex.defaultTransparency = 80; //INT 1-100 (%)
//	cvi_reflex.defaultBorder = 0; //INT 0-20 (px)
//	cvi_reflex.defaultColor = '#ffffff'; //STR '#000000'-'#ffffff'
//	cvi_reflex.defaultBoxmode = false; //BOOLEAN
    $$('div.ctx-head').each(function(el) {
        var playbutton = $("yupoostream_"+el.id);
        if (playbutton == null) {
            playbutton = document.createElement("div");
            playbutton.setAttribute("id","yupoostream_"+el.id);
            playbutton.setAttribute("title","点击播放");
            playbutton.setAttribute("class","yupoostream_playbutton");
            
            var pEle = el.getParent();
            if (pEle.hasClass('album')) {
	            var match = pEle.id.match(/^ctx_album_([0-9a-z]{32})_(\d+)$/);
	            if (match) {
	            } else {
	                match = pEle.id.match(/^ctx_album_([0-9a-z]{32})_(\d+)_([0-9a-z]{32})$/);
	            }
                initValue = {type:'album', id:match[1]};
	            playbutton.setAttribute("onclick", "init({type:'album', id:'"+match[1]+"'});");
            } else if (pEle.hasClass('pool')) {
                var match = pEle.id.match(/^ctx_pool_([0-9a-z]{32})_(\d+)$/);
                if ( !match ) {
                    match = pEle.id.match(/^ctx_pool_([0-9a-z]{32})_(\d+)_([0-9a-z]{32})$/);
                }
	            playbutton.setAttribute("onclick", "init({type:'pool', id:'"+match[1]+"'});");
            } else {
	            playbutton.setAttribute("onclick", "init();");
            }
            el.appendChild(playbutton);
        }
    });
}

function keydown(event) {
    var e = event;
    if ($('yupoostream_back')) {
	    switch (e.keyCode) {
            case 27: 
                quit();
                break;
            case 39:
            case 78:
                next();
                break;
            case 37:
            case 80:
                prev();
                break;
            default:
                break;
        }
    }
}
window.addEventListener("load", yupoostreamload, false);
window.addEventListener("resize", resize, false);
window.addEventListener("keydown", keydown, false);